﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.GDFG;
using StateGrid.User;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class AddPM : System.Web.UI.Page
{
    /// <summary>
    /// 国电法规操作对象
    /// </summary>
    private GDFG_DAO gdfgDAO = new GDFG_DAO();
    /// <summary>
    /// 日志操作对象
    /// </summary>
    private OperationLog_DAO operationLogDAO = new OperationLog_DAO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }

        if (!this.IsPostBack)
        {
            this.BindData();
        }

    }

    /// <summary>
    /// 绑定初始化数据
    /// </summary>
    private void BindData()
    {
        
        String message = null;
        String wjm = HttpUtility.UrlDecode(Request["wjm"]);
        if (null == wjm || "".Equals(wjm))
        {
            message = "错误：参数错误";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }

        //指定文件名的法规文件
        GDFG_PM gdfgPM = this.gdfgDAO.GetGDFG_PMByWjm(wjm);

        if (null == gdfgPM)
        {
            message = "错误：没有找到该国电法规";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }

        //获取对应的分类信息
        GDFG_FL gdfgFL = this.gdfgDAO.GetGDFG_FLByFlbm(gdfgPM.flbm);

        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return;
        }
        //登录人
        this.dlrTextBox.Text = user.name;

        //设置文件名
        this.pdfHyperLink.Text = gdfgPM.wjm;
        this.pdfHyperLink.NavigateUrl = GlobalResource.VIEW_PAGE + "?fileName=" + gdfgPM.wjm;

        //设置返回按钮链接
        this.backHyperLink.NavigateUrl = GlobalGDFG.LISTPM_PAGE + "?catalog=" + gdfgPM.flbm;
        //分类编码
        this.flbmTextBox.Text = gdfgFL.flbm;
        //分类名称
        this.flmcTextBox.Text = gdfgFL.flmc;
        //索引编码
        this.sybmTextBox.Text= gdfgPM.sybm;
        //发布年份
        this.fbnfTextBox.Text = gdfgPM.sybm.Split('-')[1];

        //法规文号
        this.fgwhTextBox.Text = gdfgPM.fgwh;
        //法规名称
        this.fgmcTextBox.Text = gdfgPM.fgmc;
        //发布单位
        this.fbdwTextBox.Text = gdfgPM.fbdw;
        //专业分类
        this.zyflTextBox.Text = gdfgPM.zyfl;
        //发布日期
        DateTime dt;
        if (null != gdfgPM.fbrq)
        {
            dt = (DateTime)gdfgPM.fbrq;
            this.fbrqTextBox.Text = dt.ToString("yyyy-MM-dd");
        }
        //实施日期
        if (null != gdfgPM.ssrq)
        {
            dt = (DateTime)gdfgPM.ssrq;
            this.ssrqTextBox.Text = dt.ToString("yyyy-MM-dd");
        }
        //失效日期
        if (null != gdfgPM.sxrq)
        {
            dt = (DateTime)gdfgPM.sxrq;
            this.sxrqTextBox.Text = dt.ToString("yyyy-MM-dd");
        }
        //开放
        this.kfCheckBox.Checked = gdfgPM.kf;
        //全文检查
        this.qwjcCheckBox.Checked = gdfgPM.qwjc;
        //时效
        this.sxTextBox.Text = gdfgPM.sx;
        //开本
        this.kbTextBox.Text = gdfgPM.kb;
        //页数
        this.ysTextBox.Text = gdfgPM.ys.ToString();
        //更新项
        this.gxxTextBox.Text = gdfgPM.gxx;
        //备注
        this.bzTextBox.Text = gdfgPM.bz;

        this.SetPreAndNextPM();
    }

    /// <summary>
    /// 获取用户填写的国电法规篇名信息
    /// </summary>
    /// <returns></returns>
    private GDFG_PM GetGDFGPM()
    {
        GDFG_PM gdfgPM = new GDFG_PM();
        //索引编码
        gdfgPM.sybm = this.sybmTextBox.Text;
        //分类编码
        gdfgPM.flbm = this.flbmTextBox.Text;
        //文件名
        gdfgPM.wjm = this.pdfHyperLink.Text;
        //法规名称
        gdfgPM.fgmc = this.fgmcTextBox.Text.Trim();
        //法规文号
        gdfgPM.fgwh = this.fgwhTextBox.Text.Trim();
        //发布单位
        gdfgPM.fbdw = this.fbdwTextBox.Text.Trim();

        //发布日期
        if (!"".Equals(this.fbrqTextBox.Text))
            gdfgPM.fbrq = DateTime.Parse(this.fbrqTextBox.Text);
        //实施日期
        if (!"".Equals(this.ssrqTextBox.Text))
            gdfgPM.ssrq = DateTime.Parse(this.ssrqTextBox.Text);
        //失效日期
        if (!"".Equals(this.sxrqTextBox.Text))
            gdfgPM.sxrq = DateTime.Parse(this.sxrqTextBox.Text);

        //专业分类
        gdfgPM.zyfl = this.zyflTextBox.Text;
        //时效
        gdfgPM.sx = this.sxTextBox.Text.Trim();
        //开本
        gdfgPM.kb = this.kbTextBox.Text.Trim();
        //开放
        gdfgPM.kf = this.kfCheckBox.Checked;
        //全文检查
        gdfgPM.qwjc = this.qwjcCheckBox.Checked;

        if (!"".Equals(this.ysTextBox.Text))
            gdfgPM.ys = Int32.Parse(this.ysTextBox.Text);
        //更新项
        gdfgPM.gxx = this.gxxTextBox.Text;
        //备注
        gdfgPM.bz = this.bzTextBox.Text;
        //更新日期
        gdfgPM.gxrq = DateTime.Now;
        //登录人
        gdfgPM.dlr = this.dlrTextBox.Text.Trim();

        return gdfgPM;

    }

    protected void submitButton_Click(object sender, EventArgs e)
    {
        //验证页数
        if (!this.ValidateYS())
        {
            return;
        }

        //验证法规名称
        if (!this.ValidateFGMC())
        {
            return;
        }

        //日期验证
        if (!this.ValidateRQ(this.fbrqTextBox.Text.ToString(), "发布日期")
           || !this.ValidateRQ(this.ssrqTextBox.Text.ToString(), "实施日期")
           || !this.ValidateRQ(this.sxrqTextBox.Text.ToString(), "失效日期"))
        {
            return;
        }

        //发布年份验证
        if (!ValidateFBNF(this.fbnfTextBox.Text, this.fbrqTextBox.Text))
        {
            return;
        }

        //验证上传文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }

        if (null != this.ywjmFileUpload && null != this.ywjmFileUpload.FileName && !"".Equals(this.ywjmFileUpload.FileName))
        {
            if (!OperationFile.Upload(this.ywjmFileUpload, this.pdfHyperLink.Text))
            {
                Response.Write("<Script>alert('更新国电法规信息失败')</Script>");
                return;
            }
        }

        GDFG_PM gdfgPM = this.GetGDFGPM();

        if (this.gdfgDAO.UpdateGDFG_PM(gdfgPM, ((User)Session["login"]).name))
        {
            Response.Write("<Script>alert('更新国电法规信息成功')</Script>");
            this.NextPM();
        }
        else
        {
            Response.Write("<Script>alert('更新国电法规信息失败')</Script>");
        }
    }

    /// <summary>
    /// 验证法规名称
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateFGMC()
    {
        Boolean flag = true;

        this.errorLabel.Text = "";
        if(null==this.fgmcTextBox.Text||"".Equals(this.fgmcTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：法规名称不能为空";
            flag = false;
        }
        return flag;
    }

    /// <summary>验证日期</summary>
    private Boolean ValidateRQ(String rq, String msg)
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (rq != "")
        {
            try
            {
                DateTime val = DateTime.Parse(rq);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：" + msg + "格式不正确.";
                return false;
            }
        }
        return flag;
    }

    /// <summary>验证发布日期</summary>
    private Boolean ValidateFBNF(String fbnf, String fbrq)
    {
        Boolean flag = true;
        this.errorLabel.Text = "";

        if (!"".Equals(fbrq))
        {
            //保证发布年份相符
            if (fbrq.IndexOf(fbnf) < 0)
            {
                this.errorLabel.Text = "错误：发布年份与发布日期不符";
                flag = false;
            }
        }

        return flag;
    }
    
    /// <summary>验证页数</summary>
    private Boolean ValidateYS()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ysTextBox != null && this.ysTextBox.Text != "")
        {
            try
            {
                int val = Int32.Parse(this.ysTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：页数信息不是有效数字";
                return false;
            }
        }

        return flag;
    }

    /// <summary>
    /// 验证上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
            flag = true;
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    this.ysTextBox.Text = pdf.NumberOfPages.ToString();
                }

                pdf.Close();
            }
        }
        return flag;
    }

    protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }

   /// <summary>
   /// 设置前一篇和后一篇的链接
   /// </summary>
   private void SetPreAndNextPM()
   {
       //上一篇
       String pre = this.GetDirectionPM(-1);
       if (null != pre)
       {
           this.preHyperLink.NavigateUrl = GlobalGDFG.EDITPM_PAGE + "?wjm=" + pre;
       }

       //下一篇
       String next = this.GetDirectionPM(1);
       if (null != next)
       {
           this.nextHyperLink.NavigateUrl = GlobalGDFG.EDITPM_PAGE + "?wjm=" + next;
       }
   }
   /// <summary>
   /// 修改下一篇
   /// </summary>
   private void NextPM()
   {
       String wjm = this.GetDirectionPM(1);
       if (null == wjm)
       {
           return;
       }
       else
       {
           Response.Redirect(GlobalGDFG.EDITPM_PAGE + "?wjm=" + wjm);
       }
   }

   /// <summary>
   /// 获取下一个文件名，不包括后缀
   /// </summary>
   /// <param name="wjm"></param>
   /// <param name="direction">大于0下一篇；反之，上一篇</param>
   /// <returns></returns>
   private String GetDirectionPM(int direction)
   {
       String result = null;
       //获取文件名的后三位流水号，并在其基础上加1
       int endIndex = this.pdfHyperLink.Text.LastIndexOf(".");

       String phString = this.pdfHyperLink.Text.Substring(endIndex - 3, 3);

       int ph = 0;

       try
       {
           ph = Int32.Parse(phString);
       }
       catch (Exception)
       {
       }

       //当前篇号+1或-1
       if (direction > 0)
       {
           ph++;
       }
       else
       {
           ph--;
       }

       phString = ph.ToString();
       //长度为1
       if (phString.Length == 1)
       {
           phString = "00" + phString;
       }
       else if (phString.Length == 2)
       {
           phString = "0" + phString;
       }

       result = this.sybmTextBox.Text + "-" + phString + ".PDF";
       GDFG_PM GDFGPM = this.gdfgDAO.GetGDFG_PMByWjm(result);
       if (null == GDFGPM)
       {
           return null;
       }
       return result;
   }
}